package task

import (
	"crawler/tools"
	"encoding/json"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/ying32/govcl/vcl"
	"io/ioutil"
	"net/http"
	"os"
	path2 "path"
	filepath2 "path/filepath"
	"strconv"
)

var getUrl = "https://huodong.fanli.com/Pddlijin/ajaxProList?&scene_id=335&prd=0"

type Response struct {
	Info string `json:"info"`
	Data struct {
		List []*Good `json:"list"`
	} `json:"data"`
	Status int `json:"status"`
}

var header = map[string]string{"A1": "商品id", "B1": "商品标题", "C1": "原价", "D1": "商品图片", "E1": "优惠券面额",
	"F1": "券后价", "G1": "商品销量", "H1": "标签", "I1": "折扣", "J1": "标签全称", "K1": "活动id", "L1": "商品签名id", "M1": "招商团长id"}

type Good struct {
	ProID        string  `json:"pro_id"`
	ProName      string  `json:"pro_name"`
	ProPrice     float64 `json:"pro_price"`
	ImageURL     string  `json:"image_url"`
	CouponAmount int     `json:"coupon_amount"`
	FinalPrice   float64 `json:"final_price"`
	SalesTip     string  `json:"sales_tip"`
	Tag          string  `json:"tag"`
	//IsReceive    int           `json:"is_receive"`
	Discount float64 `json:"discount"`
	//WeAppInfo    []interface{} `json:"we_app_info"`
	TagQuantext string `json:"tag_quantext"`
	GoodsSign   string `json:"goods_sign"`
	ZsDuoId     string  `json:"zs_duo_id"`
}

func Run() {
	if GetStatus() == 2 {
		tools.ShowMessage("任务已经在运行中")
		return
	}
	SetStatus(2)
	defer func() {
		if err := recover(); err != nil {
			msg := fmt.Sprintf("%v", err)
			tools.ShowMessage("出现错误:" + msg)
			Stop()
		} else {
			Stop()
			tools.ShowMessage("任务已经完成")
		}

	}()
	vcl.ThreadSync(func() {

		//Form1.Button2.SetEnabled(true)
		Form1.Button2.SetCaption("停止任务")
	})
	var page = 1
	//创建文件目录
	path, err := filepath2.Abs("./data")
	if err != nil {
		panic(err)
	}
	if !Exists(path) {
		err := os.Mkdir(path, 0644)
		if err != nil {
			panic("创建data目录失败")
		}
	}
	filepath := path2.Join(path, "data.xlsx")
	excel := excelize.NewFile()
	index := excel.NewSheet("Sheet1")
	excel.SetActiveSheet(index)
	for k, v := range header {
		excel.SetCellValue("Sheet1", k, v)

	}
	if err != nil {
		panic(err)
	}
	var line = 2
End:
	for {
		res := GetResponse(page)
		if len(res.Data.List) <= 0 || GetStatus() != 2 {
			break End
		}
		for _, good := range res.Data.List {
			excel.SetSheetRow("Sheet1", fmt.Sprintf("A%d", line), &[]interface{}{
				good.ProID,
				good.ProName,
				good.ProPrice,
				good.ImageURL,
				good.CouponAmount,
				good.FinalPrice,
				good.SalesTip,
				good.Tag,
				good.Discount,
				good.TagQuantext, 2,good.GoodsSign,good.ZsDuoId})

			if err != nil {
				panic(err)
			}
			line++
		}
		fmt.Println(page)
		page++
	}
	err = excel.SaveAs(filepath)
	if err != nil {
		panic(err)
	}

}

// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
	_, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}
func Stop() {
	SetStatus(1)
	vcl.ThreadSync(func() {

		//Form1.Button2.SetEnabled(true)
		Form1.Button2.SetCaption("开始任务")
	})
}
func GetResponse(page int) *Response {
	u := getUrl + "&p=" + strconv.Itoa(page)
	res, err := http.Get(u)
	if err != nil {
		panic("网络错误")
	}
	fmt.Println(u)
	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic("读取数据：" + err.Error())
	}
	var rData = new(Response)
	err = json.Unmarshal(data, rData)
	if err != nil {
		panic("json解析错误：" + err.Error())
	}
	return rData
}
